<template>
  <section>
    <div class="title">产品规格设置</div>
    <div class="spec-line" v-for="(item, index) in specData" :key="index">
      <div class="pb10">
        <span v-if="!cachespecData[index].status">{{ item.text }}</span>
        <el-input size="small" placeholder="请输入规格" v-if="cachespecData[index].status" v-model="cachespecData[index].text" @keyup.native.enter="handleSave(index)">
          <el-button type="primary" slot="append" icon="el-icon-check" @click="handleSave(index)"></el-button>
        </el-input>
        <i class="icon el-icon-edit" v-if="!cachespecData[index].status" @click="handleSaveUpdate(index)"></i>
      </div>
      <div>
        <el-tag v-for="(tag, j) in item.values" :key="j" @close="delSpecTag(index, j)" closable>{{ tag.text }}</el-tag>
        <el-input size="small" placeholder="多个属性用空格隔开" v-model="addValues[index]" @keyup.native.enter="handleAddTag(index)">
          <el-button slot="append" icon="el-icon-check" type="primary" @click="handleAddTag(index)"></el-button>
        </el-input>
      </div>
      <i class="icon el-icon-circle-close spec-deleted" @click="handlerDel(index)"></i>
      <el-divider></el-divider>
    </div>
    <div class="add-spec">
      <el-button size="small" type="primary" :disabled="specData.length >= 3" @click="handleAdd" >添加规格</el-button>
    </div>
  </section>
</template>

<script type="text/ecmascript-6">
import specMixins from "./mixins"
import { objEquals } from "./fn"
export default {
  data() {
    return {
      addValues: [],
      cachespecData: [],
    }
  },
  mixins: [specMixins],
  watch: {
    specData: {
      handler(data) {
        if(data && data.length > 0) this.$emit("change-data", data)
      },
      deep: true,
      immediate: true
    },
    specTable: {
      handler(data) {
        if(data && data.length > 0) this.$emit("change-table", data)
      },
      deep: true,
      immediate: true
    },
  },
  computed: {
    stockSpecArr() {
      return this.specTable.map((item) => item.data)
    },
  },
  methods: {
    // 添加
    handleAdd() {
      if (this.specData.length < 5) {
        // const id = Date.now()
        const id = Math.random().toFixed(6).slice(-6) // 随机生成六位数验证码
        console.log(typeof id, id)
        this.cachespecData.push({ id, text: "", status: true })
        this.specData.push({ id, text: "", values: [] })
      }
    },
    handleSave(index) {
      if (!this.cachespecData[index].text.trim()) {
        this.$message.error('规格不能为空！')
        return
      }
      if (this.specData[index].text === this.cachespecData[index].text) {
        this.cachespecData[index].status = false
      } else {
        if (this.verifyRepeat(index)) {
          this.$message.error('规格重复！')
        } else {
          this.specData[index].text = this.cachespecData[index].text
          this.cachespecData[index].status = false
        }
      }
    },
    // 更新状态
    handleSaveUpdate(index) {
      this.cachespecData[index].status = true
      this.cachespecData[index].text = this.specData[index].text
    },
    // 添加规格
    handleAddTag(index) {
      if (!this.cachespecData[index].text.trim()) {
        this.$message.error('规格不能为空！')
        return
      }
      let str = this.addValues[index] || ""
      if (!str.trim() || !this.cachespecData[index].text.trim()) {
        this.$message.error("属性不能为空！")
        return
      }
      let flag = false
      this.specData[index].values.forEach(item => {
        if(item.text === str) flag = true
      })
      if(flag) {
        this.$message.error("属性重复！")
        return
      }

      str = str.trim()
      let arr = str.split(/\s+/)
      let tempArr = []
      // const id = Date.now()
      const id = Math.random().toFixed(6).slice(-6) // 随机生成六位数验证码
      arr.forEach(item => {
        tempArr.push({ id, text: item })
      })
      let newArr = this.specData[index].values.concat(tempArr)
      newArr = Array.from(new Set(newArr))
      this.$set(this.specData[index], "values", newArr)

      this.clearAddValues(index)
      this.specChange("add")

      this.specData[index].text = this.cachespecData[index].text
      this.cachespecData[index].status = false
    },
    // 删除
    delSpecTag(index, num) {
      const sd = this.specData[index].values[num]
      this.$confirm(`是否删除【${sd.text}】规格？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(this.specData[index].values[num])
        this.specData[index].values.splice(num, 1)
        if(this.specData[index].values.length <= 0) {
          this.specData.splice(index, 1)
          this.cachespecData.splice(index, 1)
        }
        this.specChange("del")
        this.$message({ type: 'success', message: '删除成功!' })
      }).catch(err => {})
    },
    handlerDel(index) {
      const sd = this.specData[index]
      this.$confirm(`是否删除【${sd.text}】产品规格？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.specData.splice(index, 1)
        this.cachespecData.splice(index, 1)
        this.specChange("del")
        this.$message({ type: 'success', message: '删除成功!' })
      }).catch(err => {})
    },
    verifyRepeat(index) {
      let flag = false
      this.specData.forEach((v, j) => {
        if (index !== j) {
          if (this.specData[j].text === this.cachespecData[index].text) flag = true
        }
      })
      return flag
    },
    // 删除
    clearAddValues(index) {
      this.$set(this.addValues, index, "")
    },
    specChange(option) {
      const stockCopy = this.specTable
      if (option === "del") {
        this.specTable = []
      }
      for (let i = 0; i < this.SKUNums; i++) {
        this.changeStock(option, i, stockCopy)
      }
    },
    // 动态更改库存相关信息
    changeStock(option, index, stockCopy) {
      const spec = this.getSpecId(index)
      if (option === "add") {
        let len = this.stockSpecArr.length
        if (len) {
          for (let i = 0; i < len; i++) {
            if (!objEquals(spec, this.stockSpecArr[i])) {
              this.$set(this.specTable, index, this.creatChildProduct(index))
              return
            }
          }
        } else {
          this.$set(this.specTable, index, this.creatChildProduct(index))
        }
      } else if (option === "del") {
        let origin = ""
        let len = stockCopy.length
        for (let i = 0; i < len; i++) {
          if (objEquals(spec, stockCopy[i].data)) origin = stockCopy[i]
        }
        this.specTable.push(origin || this.creatChildProduct(index))
      }
    },
    // 获取 specTable
    getSpecId(index) {
      let obj = {}
      this.specData.forEach((item, specIndex) => {
        obj[item.text] = this.getSpecAttr(specIndex, index)
      })
      return obj
    },
    getSpecData(index) {
      let tempArr = []
      this.specData.forEach((item, specIndex) => {
        tempArr.push({
          id: Date.now(),
          name: item.text,
          value_id: item.id,
          value_name: this.getSpecAttr(specIndex, index),
        })
      })
      return tempArr
    },
    // 规格
    creatChildProduct(index) {
      let childProduct = {}
      childProduct["id"] = Date.now()
      childProduct["data"] = this.getSpecData(index)
      childProduct["isUse"] = true
      childProduct["picArr"] = []
      this.thList.forEach(item => {
        if (item.form == "skuNo") {
          // childProduct["skuNo"] = this.defaultProductNo + index

          childProduct["skuNo"] = this.defaultProductNo + Number(index + 1)
          if (childProduct["skuNo"] < 10) {
            childProduct["skuNo"] = 0 + this.defaultProductNo + Number(index + 1)
          }
        } else {
          if(item.form == "pic") {
            childProduct["pic"] = []
          } else {
            childProduct[item.form] = ""
          }
        }
      })
      return childProduct
    },
  },
}
</script>

<style scoped lang="scss">
>>> {
  .el-input {
    width: 300px;
  }
  .spec-deleted {
    position: absolute;
    right: 0;
    top: 0;
    display: none;
    cursor: pointer;
  }
  .el-tag {
    margin-right: 3px;
  }
}
.spec-line {
  position: relative;
  &:hover >>> .spec-deleted{
    display: inline;
  }
}
.title {
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #EBEEF5;
}
.pb10 {
  padding-bottom: 10px;
}
</style>
